package pt.fct.mpc.lastfm.connectivity.bt;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

public class LastfmBluetoothGateway
{
	
	private static final String TAG = "Last.fm BT Gateway";
	
	private String remote_uuid_str;
	private BluetoothAdapter bt_adapter;
	private BluetoothSocket bt_socket;
	private BluetoothDevice remote_device;
	private UUID remote_uuid;

	private InputStream in;

	private OutputStream out;

	public LastfmBluetoothGateway(String address, String uuid) 
		throws LastfmBluetoothException
	{
		this.remote_uuid_str = uuid;
		
		this.bt_adapter = BluetoothAdapter.getDefaultAdapter();
		this.remote_device = this.bt_adapter.getRemoteDevice(address);
		this.remote_uuid = UUID.fromString(remote_uuid_str);
		
		doGatewayGreeting();
	}

	public void destroy()
	{
		
	}
	
	public void beginConnection() 
		throws LastfmBluetoothException
	{
		if (remote_device == null)
		{
			Log.d(TAG, "Remote device is null.");
			throw new LastfmBluetoothException("Remote device is null");
		}
		
		try
		{
			if (this.bt_socket != null) 
				this.endConnection();
			
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		
		Log.d(TAG, "Connecting to "+remote_device.getName());
		try
		{
			this.bt_socket = 
				remote_device.createRfcommSocketToServiceRecord(remote_uuid);
			this.bt_socket.connect();
			
			this.in = this.bt_socket.getInputStream();
			this.out = this.bt_socket.getOutputStream();
			
		} catch (IOException e)
		{
			e.printStackTrace();
			
			try
			{
				this.bt_socket.close();
			} catch (IOException e1)
			{
				e1.printStackTrace();
			}
			
			throw new LastfmBluetoothException(e.getMessage());
		}
	}

	public void endConnection() 
		throws IOException
	{
		if (this.in != null)
			this.in.close();
		
		if (this.out != null)
			this.out.close();
		
		if (this.bt_socket != null)
			this.bt_socket.close();
	
		this.in = null;
		this.out = null;
		this.bt_socket = null;
	}
	
	public InputStream getInputStream() 
		throws IOException
	{
		return new LastfmBluetoothInputStream(this.in);
	}
	
	public OutputStream getOutputStream()
	{
		return this.out;
	}

	private void doGatewayGreeting()
			throws LastfmBluetoothException
	{
		beginConnection();

		try
		{
			BufferedWriter writer =
				new BufferedWriter(new OutputStreamWriter(out));

			writer.write("Hi there, gateway! o/\n");
			Log.d(TAG, "String to gateway written.");
			writer.flush();
			Log.d(TAG, "String to gateway flushed.");
			out.flush();
			Log.d(TAG, "OutputStream flushed.");
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				endConnection();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

}
